package net.pimpas.scanner;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import net.pimpas.core.configuration.file.DefaultFileConfiguration;
import net.pimpas.core.configuration.file.FileConfiguration;
import net.pimpas.core.scanner.Scanner;
import net.pimpas.core.scanner.exception.ScannerException;
import net.pimpas.util.EqualsHelper;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.log4j.Logger;

public class PimpasFrameworkScanner implements Scanner<FileConfiguration> {
	
	private List<FileConfiguration> filesConfiguration;
	private static final Logger logger = Logger.getLogger(PimpasFrameworkScanner.class);
	
	public PimpasFrameworkScanner() {
		this.setFilesConfiguration(new ArrayList<FileConfiguration>());
	}

	public List<FileConfiguration> getFilesConfiguration() {
		return this.filesConfiguration;
	}

	public String getName() {
		return this.getClass().getSimpleName();
	}

	public void scan() throws ScannerException {
		try {
			Enumeration<URL> enumerator = this.getClass().getClassLoader().getResources("pimpas-config.xml");
			if(!enumerator.hasMoreElements()) {
				logger.info("[PIMPAS FRAMEWORK SCANNER]: Cannot find pimpas-config.xml. Framework configuration will skip xml config.");
				return;
			}
			URL url = null;
			while(enumerator.hasMoreElements()) {
				url = enumerator.nextElement();
				this.getFilesConfiguration().add(new DefaultFileConfiguration(url, url.openStream()));
			}
		} catch (IOException e) {
			throw new ScannerException(e);
		}
	}

	public void setFilesConfiguration(List<FileConfiguration> filesConfiguration) {
		this.filesConfiguration = filesConfiguration;
	}

	public List<FileConfiguration> getResults() {
		return this.getFilesConfiguration();
	}
	
	@Override
	public int hashCode() {
		return new HashCodeBuilder()
			.append(this.getFilesConfiguration()).toHashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		return EqualsHelper.equals(this, obj);
	}
}